<template>
  <transition :name="directionName">
    <slot></slot>
  </transition>
</template>

<script setup>
import {defineProps, onMounted, watch} from 'vue'
import {useRoute} from "vue-router"

const props = defineProps(['indexPagePath'])
const route = useRoute()

let directionName = '' // 页面切换方向：slide-left左滑前进，slide-right右滑后退,
let routeStack = [] // 存储路由栈


watch(route,(val) => {
    handleRouteChange(val)
})

onMounted(()=>{
  routeStack = getSessionRouteStack() || [{ path: props.indexPagePath }]
})


const handleRouteChange = (to) => {
  const len = routeStack.length
  const currentRoute = routeStack[len - 1]
  // 判断是否是刷新路由
  if (currentRoute.path !== to.path) {
    if (len === 1) {
      // 初次打开非首页路由，前进
      setPageForward(to)
    } else {
      // len > 1
      const lastRoute = routeStack[len - 2]
      if (lastRoute.path === to.path) {
        // 打开上一页路由，后退
        setPageBack(currentRoute)
      } else {
        if (to.path === props.indexPagePath) {
          // 中途打开首页，后退，重置路由栈
          setDirectionName('slide-right')
          resetRouteStack()
        } else {
          // 常规情况，前进
          setPageForward(to)
        }
      }
    }
  }
}
// 前进
const setPageForward = (route) => {
  setDirectionName('slide-left')
  pushRouteStack(route)
}
// 后退
const setPageBack = () => {
  setDirectionName('slide-right')
  popRouteStack()
}
// 设置页面方向
const setDirectionName = (name) => {
  directionName = name
}
// 重置
const resetRouteStack = () => {
  routeStack = [{ path: props.indexPagePath }]
  setSessionRouteStack()
}
const pushRouteStack = (route) => {
  const { path } = route
  routeStack.push({ path })
  setSessionRouteStack()
}
const popRouteStack = () => {
  routeStack.pop()
  setSessionRouteStack()
}
const setSessionRouteStack = () => {
  try {
    sessionStorage.setItem('routeStack', JSON.stringify(routeStack))
  } catch (error) {
    console.warn('storage is not supported')
  }
}
const getSessionRouteStack = () => {
  const str = sessionStorage.getItem('routeStack')
  if (!str) {
    return null
  }
  let val = []
  try {
    val = JSON.parse(str)
  } catch (error) {
    console.warn('parse routeStack wrong')
  }
  return val
}

</script>

<style lang="less" scoped>
@distanceX: 100%;

.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  position: absolute;
  width: 100%;
  transition: all 0.3s cubic-bezier(0.55, 0, 0.1, 1);
}

.slide-left-enter,
.slide-left-enter-from,
.slide-right-leave-active {
  opacity: 0;
  transform: translate(@distanceX, 0);

}
.slide-left-leave-active,
.slide-right-enter,
.slide-right-enter-from{
  opacity: 0;
  transform: translate(-@distanceX, 0);
}
</style>
